#include "beautification.h"
#include "verifier.h"

Trace Beautification::beautify(Trace &t){
    SegmentVerifier verifier;
    if ( verifier.verifyTrace(t) ){
        Trace bt;
        bt.addCursor(t[0]);
        bt.addCursor(t[-1]);
        return bt;
    }
    else{
        return NULL;
    }
}

void Beautification::addPossibility(vector<Trace> &possibilities, Trace &trace, bool priority){
    bool near = false;
    for (int i = 0; i < possibilities.size(); i++){
        if ( (trace[0].distance(possibilities[i][0]) < 0.3 
             and trace[-1].distance(possibilities[i][-1]) < 0.3 )
          or (trace[0].distance(possibilities[i][-1]) < 0.3 
             and trace[-1].distance(possibilities[i][0]) < 0.3 ) ){
            // TODO: melhorar
            if (priority){
                possibilities[i] = trace;
            }
            near = true;
            break;
        }
    }
    if (!near){
        possibilities.push_back(trace);
    }
}

void Beautification::position(Trace &t){
    SegmentVerifier verifier;
    if ( verifier.verifyTrace(t) ){
        if (t.size() > 2) t.erase(1, t.size()-1);
    }
    else{
        t.clear();
    }
}

void Beautification::connections(vector<Trace> &traces, Trace &t){
    Trace connection;
    SegmentVerifier verifier;
    if ( verifier.verifyTrace(t) ){
        bool modified = false;
        
        connection.addCursor(t[0]);
        connection.addCursor(t[1]);
        connection.setId(t.getId());
            
        for (int i = 0; i < traces.size(); i++){
//            printf("Distancias: %f    %f    %f    %f\n",
//                        t[0].getScenePoint().distance(traces[i][0].getScenePoint()),
//                        t[0].getScenePoint().distance(traces[i][1].getScenePoint()),
//                        t[1].getScenePoint().distance(traces[i][0].getScenePoint()),
//                        t[1].getScenePoint().distance(traces[i][1].getScenePoint())
//                  );
        
            if (t.getId() != traces[i].getId() ){
                if ( t[0].getScenePoint().distance(traces[i][0].getScenePoint()) < 1.0 ){
                    connection[0] = traces[i][0];
                    modified = true;
                }
                if ( t[0].getScenePoint().distance(traces[i][1].getScenePoint()) < 1.0 ){
                    connection[0] = traces[i][1];
                    modified = true;
                }
                if ( t[1].getScenePoint().distance(traces[i][0].getScenePoint()) < 1.0 ){
                    connection[1] = traces[i][0];
                    modified = true;
                }     
                if ( t[1].getScenePoint().distance(traces[i][1].getScenePoint()) < 1.0 ){
                    connection[1] = traces[i][1];
                    modified = true;
                }
            }
        }
        if (modified){
            t = connection;
        }
        traces.push_back(t);
    }
}

